<template>
    <div>
        <!-- 面包屑导航栏 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 弹出警告框 -->
            <el-alert title="注意：只允许第三级分类设置相关参数" type="warning" show-icon></el-alert>
            <!-- 选择商品分类 -->
            <el-row class="selectGoodsCate">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 级联选择框 -->
                    <el-cascader v-model="goodsCateKeys" :options="goodsCateList" :props="goodsCateProps" @change="handleChange" clearable></el-cascader>
                </el-col>
            </el-row>
            <!-- Tabs标签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="showAddParams">添加参数</el-button>
                    <el-table :data="manyTableData">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close='removeTag(i,scope.row)'>{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParams(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-edit" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="showAddParams">添加属性</el-button>
                    <el-table :data="onlyTableData">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="item in scope.row.attr_vals" :key="item.id" closable @close='removeTag(i,scope.row)'>{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParams(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-edit" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加' + titleText"  :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsClosed">
            <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addparams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改' + titleText"  :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsClosed">
            <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editparams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return {
            goodsCateList:[],
            goodsCateProps:{
                expandTrigger: 'hover' ,
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            goodsCateKeys: [],
            activeName:'many',
            manyTableData: [],
            onlyTableData: [],
            addParamsDialogVisible: false,
            addParamsForm:{
                attr_name:''
            },
            addParamsFormRules:{
                attr_name: [
                    { required: true, message: '请输入参数名', trigger: 'blur' }
                ],
            },
            editParamsDialogVisible: false,
            editParamsForm:{
                attr_name:'',
                attr_id:''
            },
            editParamsFormRules:{
                attr_name: [
                    { required: true, message: '请输入参数名', trigger: 'blur' }
                ],
            },
            
        }
    },
    created(){
        this.getGoodsCateList();
    },
    methods:{
        //动态获取商品分类列表
        async getGoodsCateList(){
           const {data : res} = await this.$http.get('categories');
            if(res.meta.status != 200) return this.$message.error('获取商品分类信息失败');
            // console.log(res.data);
            this.goodsCateList = res.data;
        },
        //tab标签发生改变时触发
        handleChange(){
            this.getParamsList();
        },
        handleClick(tab,event){
            console.log(tab.name);
            this.getParamsList();
        },
        //动态获取并渲染参数列表
        async getParamsList(){
            if(this.goodsCateKeys.length !== 3)  return this.goodsCateKeys = [];
            // console.log(this.goodsCateKeys);
            const {data : res} = await this.$http.get(`categories/${this.CateId}/attributes`,{params:{sel:this.activeName}});
            if(res.meta.status != 200) return this.$message.error('获取参数列表失败');
            //将参数项中的特点字符串转换为数组
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals != '' ? item.attr_vals.split(' ') : [];
                item.inputVisible = false;
                item.inputValue = '';
            })
            console.log(res.data);
            if(this.activeName == 'many')
                this.manyTableData = res.data;
            else
                this.onlyTableData = res.data;
        },
        showAddParams(){
            this.addParamsDialogVisible = true;
        },
        addParamsClosed(){
            this.$refs.addParamsFormRef.resetFields();
        },
        //添加参数功能
        addparams(){
            this.$refs.addParamsFormRef.validate(async valid=>{
                if(!valid) return this.$message.error('请输入合法的参数');
                const {data : res} =await this.$http.post(`categories/${this.CateId}/attributes`,{
                    attr_name : this.addParamsForm.attr_name,
                    attr_sel: this.activeName
                })
                if(res.meta.status != 201) return this.$message.error('添加参数失败');
                this.$message.success('添加参数成功');
                this.addParamsDialogVisible = false;
                this.getParamsList();
            })
        },
        //显示编辑参数对话框以及动态渲染参数表单中的数据
        async showEditParams(attr_id){
            const {data : res} = await this.$http.get(`categories/${this.CateId}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}});
            if(res.meta.status != 200) return this.$message.error('获取参数失败');
            this.editParamsForm.attr_name = res.data.attr_name;
            this.editParamsForm.attr_id = attr_id;
            this.editParamsDialogVisible = true;
        },
        editParamsClosed(){
            this.$refs.editParamsFormRef.resetFields();
            this.editParamsDialogVisible = false;
        },
        //编辑参数功能
        editparams(){
            this.$refs.editParamsFormRef.validate(async valid=>{
                if(!valid) return this.$message.error('请输入合法的参数');
                const {data : res} =await this.$http.put(`categories/${this.CateId}/attributes/${this.editParamsForm.attr_id}`,{
                    attr_name : this.editParamsForm.attr_name,
                    attr_sel: this.activeName
                })
                if(res.meta.status != 200) return this.$message.error('修改参数失败');
                this.$message.success('修改参数成功');
                this.editParamsDialogVisible = false;
                this.getParamsList();
            })
        },
        //删除参数操作
        async removeParams(attr_id){
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if(confirmResult != 'confirm') return this.$message.info('已取消删除');
            const {data : res} = await this.$http.delete(`categories/${this.CateId}/attributes/${attr_id}`)
            if(res.meta.status != 200) return this.$message.error('删除失败');
            this.$message.success('删除成功');
            this.getParamsList();
        },
        //添加对应的参数可选项
        async handleInputConfirm(row){
            console.log(row)
            if(row.inputValue.trim().length === 0){
                row.inputValue = '';
                row.inputVisible = false;
                return;
            }
            row.attr_vals.push(row.inputValue.trim());
            this.saveAttrVal(row);
            row.inputValue = '';
            row.inputVisible = false;

        },
        showInput(row){
            row.inputVisible = true;
            //DOM元素渲染结束后执行该回调函数，使得input输入框获取到焦点
            this.$nextTick(_ => {
                // console.log(this.$refs.saveTagInput);
                // this.$refs.saveTagInput.$refs.input.focus();
                this.$refs.saveTagInput.focus();
            });
        },
        //删除对应的参数可选项
        removeTag(i,row){
            row.attr_vals.splice(i,1);
            this.saveAttrVal(row);
        },
        //将对应的参数可选项提交到后台服务器
        async saveAttrVal(row){
            const {data : res} = await this.$http.put(`categories/${this.CateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' ')
            })
            if(res.meta.status != 200) return this.$message.error('新增失败');
            this.$message.success('更新成功');
        }
    },
    computed:{
        isBtnDisable(){
            return this.goodsCateKeys.length === 3 ? false : true;
        },
        CateId(){
            return this.goodsCateKeys.length === 3 ? this.goodsCateKeys[2] : null;
        },
        titleText(){
            return this.activeName == 'many' ? '动态参数' : '静态属性';
        }
    }

}
</script>
<style lang="less" scoped>
    .selectGoodsCate {
        margin: 15px 0;
    }
    .el-tag {
        margin: 5px;
    }
    .input-new-tag {
        width: 120px;
    }
</style>